<template>
  <div class="productList">
    <CommonHeader title="商品列表">
      <template #left>
        <div>
          <Icon name="zuojiantou" />
          <span>返回</span>
        </div>
      </template>
    </CommonHeader>
    <!-- search + nav  -->
    <div class="productList_search_nav">
      <div class="productList_search">
        <Icon name="search" />
        <input
          type="text"
          placeholder="请输入搜索关键词"
          v-model="searchKeyword"
          @keyup.enter="handleSearch"
        />
      </div>
      <div class="productList_nav">
        <div
          class="productList_nav_item"
          v-for="(item, index) in navList"
          :key="item.name"
        >
          <Icon name="shaixuan" v-if="index === navList.length - 1"></Icon>
          <span>{{ item.name }}</span>
          <div class="productList_nav_item_arrow" v-if="index === 2">
            <div
              class="productList_nav_item_arrow_up"
              :class="{ active: sortType === 'price_asc' }"
              @click.stop="handleArrowClick('up')"
            ></div>
            <div
              class="productList_nav_item_arrow_down"
              :class="{ active: sortType === 'price_desc' }"
              @click.stop="handleArrowClick('down')"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <!-- 商品列表 -->
    <div
      class="productList_content"
      ref="contentRef"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      <!-- 下拉提示语 -->
      <div class="refresh">
        <!-- 下拉中 -->
        <template v-if="refreshStatus === 'pull'">
          <span>下拉刷新</span>
        </template>

        <!-- 达到阈值，可释放 -->
        <template v-else-if="refreshStatus === 'release'">
          <span>释放可刷新</span>
        </template>

        <!-- 正在加载 -->
        <template v-else-if="refreshStatus === 'loading'">
          <Icon name="zhengzaijiazai" />
          <span>正在加载中...</span>
        </template>
      </div>
      <div
        class="list_item"
        v-for="(item, index) in productList"
        :key="index"
        @click="handleClick(item.id)"
      >
        <div class="list_item_img">
          <CustomImage :src="item.img" />
        </div>
        <div class="list_item_info">
          <div
            class="list_item_info_title"
            v-highlight="{
              keyword: searchKeyword,
              color: 'red',
              backgroundColor: 'yellow',
            }"
          >
            {{ item.goodsname }}
          </div>
          <div class="list_item_info_desc">
            {{ item.goodsdesc ? item.goodsdesc : '描述信息' }}
          </div>
          <div class="list_item_info_price">
            <span>¥{{ item.price }}</span>
            <del class="market">{{ item.market_price }}</del>
          </div>
        </div>
      </div>
      <!-- 加载更多 -->
      <div class="loadMore">
        <template v-if="loadingMore">
          <Icon name="zhengzaijiazai" />
          <span>正在加载中...</span>
        </template>
        <template v-else>
          <span>{{ loadMoreText }}</span>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from '@/components/common/publicHeader/index.vue';

import Icon from '@/components/common/Icon/index.vue';
import { getGoodListAPI } from '@/api/home';
import { getSearchGoods } from '@/api/search';
import CustomImage from '@/components/common/Image/index.vue';

export default {
  name: 'productList',

  components: {
    CommonHeader,
    Icon,
    CustomImage,
  },
  data() {
    return {
      // 注意：@click.stop 阻止事件冒泡到外层 handleNavClick
      sortType: '', // '' | 'price_asc' | 'price_desc'
      activeNavIndex: 0, // 当前激活的导航项索引
      // activeNavIndex 用于高亮导航栏，比如点击“价格”后，可以高亮它
      originalProductList: [], // 用于保存原始未排序的商品列表
      searchKeyword: '',

      lastCateId: null,
      lastType: null,
      navList: [
        {
          name: '综合排序',
        },
        {
          name: '销量',
        },
        {
          name: '价格',
        },
        {
          name: '好评度',
        },
        {
          name: '店铺',
        },
        {
          name: '筛选',
        },
      ],
      productList: [],
      // 商品列表数据
      goodListParams: {
        cateid: this.$route.query.id,
        type: this.$route.query.type,
        page: 1,
        size: 6,
      },
      startY: 0,
      isDragging: false,
      isRefreshing: false,
      refreshText: '下拉刷新',
      refreshThreshold: 60,
      pullDistance: 0, // 下拉距离（0 开始）
      refreshStatus: 'pull', // 'pull', 'release', 'loading'
      initialScrollTop: 0, // 用于判断是否在顶部
      lastScrollTop: 0, // 用于判断滚动方向（可选）
      //
      loadingMore: false, // 是否正在加载更多
      hasMore: true, // 是否还有更多数据
      loadMoreText: '加载更多', // 加载更多显示文字
    };
  },
  activated() {
    // 每次组件被激活时（从 keep-alive 缓存中显示）
    const currentCateId = this.$route.query.id;
    const currentType = this.$route.query.type;

    // 判断 cateid 或 type 是否变化
    const isChanged =
      currentCateId !== this.lastCateId || currentType !== this.lastType;

    if (isChanged) {
      // 参数变了，重新请求
      this.goodListParams.cateid = currentCateId;
      this.goodListParams.type = currentType;
      this.goodListParams.page = 1; // 重置页码
      this.getGoodList();

      // 更新“上次参数”记录
      this.lastCateId = currentCateId;
      this.lastType = currentType;
    }
    // else: 参数没变，继续使用缓存数据，不请求
  },
  mounted() {
    // 组件首次加载时也要记录参数
    this.lastCateId = this.$route.query.id;
    this.lastType = this.$route.query.type;
    this.getGoodList(); // 首次加载数据
    this.$nextTick(() => {
      const el = this.$refs.contentRef;
      if (el) {
        el.style.transform = 'translate3d(0, 50px, 0)';
        el.style.transition = 'transform 0.3s ease';
        this.initialScrollTop = el.scrollTop || 0;
      }
      // ✅ 监听 window 滚动（被动监听，性能更好）
      window.addEventListener('scroll', this.handleWindowScroll, {
        passive: true,
      });
    });
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleWindowScroll);
  },
  methods: {
    // 跳转详情页
    handleClick(id) {
      this.$router.push({ name: 'detail', query: { id } });
    },
    // 获取商品列表
    async getGoodList() {
      try {
        const res = await getGoodListAPI(this.goodListParams);
        const {
          list: { goodData },
        } = res;
        // 判断有吗有的话map
        if (goodData) {
          const formattedData = goodData.map(item => {
            item.img = 'http://43.138.15.137:4000' + item.img;
            return item;
          });
          this.productList = formattedData;
          this.originalProductList = [...formattedData]; // ✅ 保存原始数据
        } else {
          this.loadMoreText = '没有更多了...';
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleTouchStart(event) {
      // 下拉刷新
      const el = this.$refs.contentRef;
      if (el.scrollTop <= 0) {
        this.startY = event.touches[0].clientY;
        this.isDragging = true;
        this.pullDistance = 0;
        // 移除过渡动画
        el.style.transition = 'none';
      } else {
        this.isDragging = false;
      }
    },
    handleTouchMove(event) {
      if (!this.isDragging || this.isRefreshing) return;

      const currentY = event.touches[0].clientY;
      const diff = currentY - this.startY;

      if (diff > 0) {
        // ✅ 阻尼效果：越拉越慢
        this.pullDistance = diff * 0.6;

        // ✅ 可选：限制最大下拉距离
        const maxPull = this.refreshThreshold * 2;
        if (this.pullDistance > maxPull) {
          this.pullDistance = maxPull;
        }

        // 更新状态
        if (this.pullDistance >= this.refreshThreshold) {
          this.refreshStatus = 'release';
        } else {
          this.refreshStatus = 'pull';
        }

        // ✅ 使用 translate3d 实现丝滑移动
        const translateY = 50 + this.pullDistance;
        const el = this.$refs.contentRef;
        el.style.transform = `translate3d(0, ${translateY}px, 0)`;

        event.preventDefault(); // 阻止页面默认滚动
      }
    },
    handleTouchEnd() {
      if (!this.isDragging || this.isRefreshing) return;

      this.isDragging = false;
      const el = this.$refs.contentRef;
      const reached = this.pullDistance >= this.refreshThreshold;

      if (reached) {
        // ✅ 改变状态，触发模板更新
        this.refreshStatus = 'loading';
        this.isRefreshing = true;

        if (el) {
          el.style.transition = 'transform 0.3s ease';
          el.style.transform = `translate3d(0, ${
            50 + this.refreshThreshold
          }px, 0)`;
        }

        this.simulateRefreshWithDelay(1500);
      } else {
        this.refreshStatus = 'pull';
        if (el) {
          el.style.transition = 'transform 0.3s ease';
          el.style.transform = 'translate3d(0, 50px, 0)';
        }
        this.pullDistance = 0;
      }
    },
    // 模拟刷新：先等待 delay 毫秒，再请求数据 + 回弹
    async simulateRefreshWithDelay(delay = 1500) {
      const el = this.$refs.contentRef;

      try {
        await new Promise(resolve => setTimeout(resolve, delay));
        await this.refreshData(); // 刷新数据
      } catch (err) {
        console.error('刷新失败:', err);
      } finally {
        this.isRefreshing = false;
        this.refreshStatus = 'pull';

        // ✅ 回弹到初始位置
        if (el) {
          el.style.transition = 'transform 0.3s ease';
          el.style.transform = 'translate3d(0, 50px, 0)';
        }

        setTimeout(() => {
          this.pullDistance = 0;
        }, 300);
      }
    },

    async refreshData() {
      this.goodListParams.page = 1;
      try {
        const res = await getGoodListAPI(this.goodListParams);
        const {
          list: { goodData },
        } = res;
        this.productList = goodData.map(item => {
          item.img = 'http://43.138.15.137:4000' + item.img;
          return item;
        });
      } catch (err) {
        console.log(err);
      }
    },

    // 上滑加载更多数据
    handleWindowScroll() {
      if (this.loadingMore || !this.hasMore || this.isRefreshing) return;
      const el = this.$refs.contentRef;
      if (!el) return;
      // 获取 .productList_content 的底部距离页面顶部的距离
      const rect = el.getBoundingClientRect();
      const contentBottom = rect.top + window.scrollY + el.scrollHeight;
      const currentScroll = window.scrollY + window.innerHeight;
      if (contentBottom - currentScroll < 100) {
        this.loadMore();
      }
    },

    // 你的 loadMore 方法保持不变 ✅
    async loadMore() {
      this.loadingMore = true;
      this.loadMoreText = '正在加载中...';

      try {
        this.goodListParams.page += 1;
        const res = await getGoodListAPI(this.goodListParams);
        const {
          list: { goodData },
        } = res;

        if (goodData && goodData.length > 0) {
          const newData = goodData.map(item => {
            item.img = 'http://43.138.15.137:4000' + item.img;
            return item;
          });

          this.productList = [...this.productList, ...newData];

          if (goodData.length < this.goodListParams.size) {
            this.hasMore = false;
            this.loadMoreText = '没有更多数据了';
          }
        } else {
          this.hasMore = false;
          this.loadMoreText = '没有更多数据了';
        }
      } catch (err) {
        console.error('加载更多失败:', err);
        this.loadMoreText = '加载失败，点击重试';
        this.goodListParams.page -= 1; // 回退页码
      } finally {
        this.loadingMore = false;
      }
    },

    // 搜索
    async handleSearch() {
      // 1. 如果搜索关键词为空，恢复原始商品列表
      if (!this.searchKeyword.trim()) {
        this.goodListParams.page = 1;
        this.hasMore = true;
        this.loadMoreText = '加载更多';
        await this.getGoodList();
        return;
      }

      // 2. 执行搜索请求
      try {
        const res = await getSearchGoods({
          keywords: this.searchKeyword.trim(),
        });

        // 确保 res 和 res.list 存在
        const { list } = res || {};

        // 3. 判断是否有匹配结果
        if (!list || list.length === 0) {
          this.productList = []; // 清空列表
          this.hasMore = false;
          this.loadMoreText = '未匹配到相关内容'; // 提示用户
          return;
        }

        // 4. 有结果：处理数据并更新
        this.productList = list.map(item => {
          item.img = 'http://43.138.15.137:4000' + item.img;
          return item;
        });

        // 5. 搜索状态下禁用“加载更多”
        this.hasMore = false;
        this.loadMoreText = '已显示所有搜索结果';
      } catch (err) {
        console.error('搜索失败:', err);
        this.productList = [];
        this.hasMore = false;
        this.loadMoreText = '搜索出错，请重试';
      }
    },
    // 排序
    handleArrowClick(type) {
      // 如果没有原始数据，说明还没加载过，直接返回
      if (!this.originalProductList.length) return;

      // 重置排序状态样式
      if (type === 'up') {
        if (this.sortType === 'price_asc') {
          // 再次点击，取消排序
          this.sortType = '';
          this.productList = [...this.originalProductList];
        } else {
          this.sortType = 'price_asc'; // 升序：低 → 高
          this.productList = [...this.originalProductList].sort(
            (a, b) => a.price - b.price
          );
        }
      } else if (type === 'down') {
        if (this.sortType === 'price_desc') {
          // 再次点击，取消排序
          this.sortType = '';
          this.productList = [...this.originalProductList];
        } else {
          this.sortType = 'price_desc'; // 降序：高 → 低
          this.productList = [...this.originalProductList].sort(
            (a, b) => b.price - a.price
          );
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.productList_search_nav {
  position: fixed;
  top: 46px;
  left: 0;
  width: 100%;
  height: 90px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 222;
  background: linear-gradient(#ff6040, #ff8a80);
  padding: 0 10px;

  .productList_search {
    width: 100%;
    height: 36px;
    background-color: #fff;
    border-radius: 25px;
    margin-top: 10px;
    display: flex;
    align-items: center;
    padding: 0 10px;
    overflow: hidden;
    flex-shrink: 0;

    input {
      width: 100%;
      height: 100%;
      font-size: 14px;
    }
  }

  .productList_nav {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .productList_nav_item {
      flex-shrink: 0;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: #fff;
      white-space: nowrap;
      position: relative;

      .productList_nav_item_arrow {
        position: absolute;
        top: 50%;
        right: -12px;
        transform: translateY(-40%);
        width: 10px;
        height: 10px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 2px;

        .productList_nav_item_arrow_up {
          width: 0;
          height: 0;
          border-left: 5px solid transparent;
          border-right: 5px solid transparent;
          border-bottom: 5px solid #fff;
          transition: all 0.3s ease-in-out;
        }

        .productList_nav_item_arrow_down {
          width: 0;
          height: 0;
          border-left: 5px solid transparent;
          border-right: 5px solid transparent;
          border-top: 5px solid #fff;
          transition: all 0.3s ease-in-out;
        }
        // 或者区分颜色
        .productList_nav_item_arrow_up.active {
          border-bottom-color: #f00;
        }

        .productList_nav_item_arrow_down.active {
          border-top-color: #f00;
        }
      }
    }
  }
}

.productList_content {
  position: relative;
  margin-top: 0;
  padding: 8px 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background-color: #fff;
  z-index: 1;
  transform: translate3d(0, 0, 0);
  will-change: transform;

  .refresh {
    width: 100%;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #999;
  }
  .loadMore {
    width: 100%;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #999;
  }

  .list_item {
    width: 100%;
    background-color: #fafafa;
    padding: 10px;
    display: flex;

    .list_item_img {
      width: 140px;
      height: 100px;
      margin-right: 10px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .list_item_info {
      width: 100%;
      height: 100px;

      .list_item_info_title {
        font-size: 14px;
        // 超出隐藏 显示2行
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        font-weight: bold;
      }

      .list_item_info_desc {
        font-size: 14px;
        color: #999;
      }

      .list_item_info_price {
        font-size: 15px;
        margin: 20px 0;
        color: #ff6600;

        .market {
          color: #999;
          font-size: 12px;
          margin-left: 4px;
        }
      }
    }
  }
}
</style>
